package edu.cmu.fithub.controller;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.text.ParseException;
import java.util.Date;
import java.util.Properties;

import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.QuartzSchedule;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class WorkoutMailJob implements Job {
	// fithubscheduler
	// issexy

	/**
	 * Empty constructor for Quartz job initialization
	 */
	public WorkoutMailJob() {
	}

	public static int addWorkoutSchedule(String emailAddress,
			String description, String schedString) {
		QuartzSchedule schedule = new QuartzSchedule(emailAddress, description,
				schedString);
		org.hibernate.Session dbSession = DBHelper.getSessionFactory()
				.openSession();
		dbSession.beginTransaction();
		dbSession.save(schedule);
		dbSession.getTransaction().commit();
		try {
			Scheduler sched = InitListener.getScheduler();
			JobDetail job = newJob(WorkoutMailJob.class)
					.withIdentity(schedule.getScheduleId() + "", "group_j")
					.usingJobData("email", emailAddress)
					.usingJobData("body", description).build();
			CronTrigger trigger = newTrigger()
					.withIdentity(schedule.getScheduleId() + "trigger",
							"group_j").withSchedule(cronSchedule(schedString))
					.forJob(job).build();
			sched.scheduleJob(job, trigger);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		return schedule.getScheduleId();
	}

	public static void removeWorkout(int scheduleId) {
		QuartzSchedule qSchedule = new QuartzSchedule();
		qSchedule.setScheduleId(scheduleId);
		org.hibernate.Session dbSession = DBHelper.getSessionFactory().openSession();
		dbSession.beginTransaction();
		dbSession.delete(qSchedule);
		dbSession.getTransaction().commit();
		try {
			Scheduler sched = InitListener.getScheduler();
			sched.deleteJob(new org.quartz.JobKey(scheduleId + "", "group_j"));
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	public static String getSchedString(String day, int hour, int min) {
		return "0 " + min + " " + hour + " ? * " + day;
	}

	/**
	 * <p>
	 * Called by the <code>{@link org.quartz.Scheduler}</code> when a
	 * <code>{@link org.quartz.Trigger}</code> fires that is associated with the
	 * <code>Job</code>.
	 * </p>
	 * 
	 * @throws JobExecutionException
	 *             if there is an exception while executing the job.
	 */
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		System.out.println("starting job");
		String to = context.getJobDetail().getJobDataMap().getString("email");
		String from = "fithubscheduler@gmail.com";
		final String username = "fithubscheduler";
		final String password = "nishantissexy";

		// create some properties and get the default Session
		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "587");

		Session session = Session.getInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				});
		try {

			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(to));
			message.setSubject("Workout Reminder");
			message.setContent(context.getJobDetail().getJobDataMap()
					.getString("body"), "text/html");

			Transport.send(message);

			System.out.println("Done");

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}